const app = getApp()
import {
  logout,
  selectDefaultPrinterInfo,
  getPhone,
  updatePhone
} from "../../common/api";
// pages/wode/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hideLogin: true,
    hideUserInfo: true,
    showUpdateModal: true,
    hideUpdatePhone: true,
    myphone: "",
    userInfo: {},
    showPop: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    const privacySettingRes = await this.getPrivacySetting();
    console.log("privacySettingRes :>> ", privacySettingRes);
    this.setData({
      showPop: privacySettingRes.needAuthorization
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.getUserInfo();
    if (app.globalData.bindphone !== undefined) {
      this.setData({
        myphone: app.globalData.bindphone
      });
    }
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo !== undefined) {
      this.setData({
        userInfo: userInfo
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  closeShowUpdateModal() {
    this.setData({
      showUpdateModal: true
    });
  },
  closeHideUpdatePhone() {
    this.setData({
      hideUpdatePhone: true
    });
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  btnUpdate() {
    let phone = this.data.inputValue
    console.log("修改的手机号", phone)
    let data = {
      "phone": phone
    }
    var that = this;
    wx.showLoading({
      title: '正在修改中...',
      mask: true,
    })
    this.setData({
      hideUpdatePhone: true,
    });
    updatePhone(data).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.removeStorageSync('bindphone')
        wx.setStorageSync("bindphone", phone)
        app.globalData.bindphone = phone;
        that.setData({
          myphone: phone
        });
      }
    })
  },
  updateUser(e) {
    let bindphone = wx.getStorageSync("bindphone")
    if (bindphone) {
      app.globalData.bindphone = bindphone
      this.setData({
        hideUpdatePhone: false,
        myphone: bindphone
      });
    } else {
      this.setData({
        showUpdateModal: false
      });
    }
  },
  getPhoneNumber: function (e) {
    var that = this;
    that.setData({
      showUpdateModal: true
    });
    wx.showLoading({
      title: '获取手机号码中...',
      mask: true,
    })
    let data = {
      "code": e.detail.code
    }
    getPhone(data).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.removeStorageSync('bindphone')
        wx.setStorageSync("bindphone", res.data.phoneNumber)
        app.globalData.bindphone = res.data.phoneNumber;
        that.setData({
          myphone: res.data.phoneNumber
        });
      }
    })
  },
  loginOut(e) {
    wx.showModal({
      title: '提示',
      content: '确定退出登录吗?',
      success(res) {
        if (res.confirm) {
          app.globalData.printer = undefined;
          app.globalData.isLogin = false;
          app.globalData.bindphone = undefined;
          wx.removeStorageSync('printer');
          wx.removeStorageSync('token');
          wx.removeStorageSync('bindphone')
          logout().then(res => {
            wx.reLaunch({
              url: '/pages/wode/index',
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  /**
   * 我的订单 和 我的文库的按钮
   * @param {} e 
   */
  zt(e) {
    let url = e.currentTarget.dataset.url;
    if (url == 'or_list') {
      wx.reLaunch({
        url: '/pages/or_list/index',
      })
    }
    if (url == 'address_list') {
      wx.reLaunch({
        url: '/pages/wode/address_list?select=false',
      })
    }
  },
  getUserInfo: function () {
    let that = this
    let isLogin = app.globalData.isLogin
    if (isLogin === false) {
      that.setData({
        hideLogin: false
      });
    }
  },
  // 点击按钮登录
  login_user: function () {
    let _this = this;
    wx.showLoading({
      title: '登录中...',
      mask: true
    })

    // 获取权限
    // wx.getUserInfo({
    //   lang: 'zh_CN',
    //   // 获取权限成功后登录
    //   success: data => {
    //     console.log(1)
    wx.login({
      success: res => {
        let code = res.code;
        let post = {
          code: code
        };
        wx.request({
          url: `${app.globalData.javaApi}/api/wx/login`,
          method: "POST",
          data: post,
          header: {
            "AppId": `${app.globalData.appId}`
          },
          success: res => {
            _this.setData({
              hideLogin: true
            })
            res = res.data;
            console.log(res)
            if (res.code === 200) {
              wx.hideLoading()
              //必须先清除，否则res.header['Set-Cookie']会报错
              wx.removeStorageSync('token');
              //储存res.header['Set-Cookie']
              wx.setStorageSync('token', res.data.token)
              wx.removeStorageSync('bindphone')
              app.globalData.bindphone = undefined
              if (res.data.phone !== "0") {
                wx.setStorageSync("bindphone", res.data.phone)
                app.globalData.bindphone = res.data.phone;
                wx.setStorageSync("userInfo", res.data)
                _this.setData({
                  myphone: res.data.phone,
                  userInfo: res.data
                });
              }
              //
              _this.setData({
                hideUserInfo: true
              });
              selectDefaultPrinterInfo();
              app.globalData.isLogin = true;
              app.globalData.isAdmin = res.data.admin;
              console.log("是否是管理员", res.data.admin)
              //if (res.data.admin) {
              //  console.log("进到这里")
                //this.dingyue()
              //}
            } else {
              wx.hideLoading()
              wx.showModal({
                title: "错误",
                content: res.msg,
                success: res => {
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                  return true;
                }
              })
            }
          }
        })
      },
    })
    //   }
    // })
  },
  dingyue() {
    wx.showModal({
      title: "提示",
      content: "管理员您好，需要订阅打印机告警消息吗?",
      cancelText: "不订阅",
      confirmText: "订阅",
      success: res => {
        if (res.confirm) {
          wx.requestSubscribeMessage({
            tmplIds: ['o4K8YLtDE9Odf6BJPula60AWBrpAq2TBFTar4Xm10q0'],
            success(res) {
              console.log("订阅告警信息成功")
            },
            fail(res) {
              console.log(res)
            }
          })
        }
      }
    })
  },
  /**
   * 按钮点击回调
   */
  popBtnTap(res) {
    console.log("授权结果返回数据 :>> ", res);
    console.log("授权结果 :>> ", res.detail);
    if (res.detail.result) {
      wx.showToast({
        title: "同意授权",
        icon: "success",
      });
    } else {
      wx.showToast({
        title: "拒绝授权",
        icon: "error",
      });
    }
  },
  /**
   * 获取隐私协议授权信息
   * @returns {object} {needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》'}
   */
  getPrivacySetting() {
    const res = {
      needAuthorization: false,
      privacyContractName: "基础库过低，不需要授权",
    };
    if (!wx.getPrivacySetting) return res;
    console.log('到这')
    return new Promise((resolve, reject) => {
      wx.getPrivacySetting({
        success(res) {
          resolve(res);
        },
        fail(err) {
          reject(err);
        },
      });
    });
  },
  updateMiniUser: function () {
    wx.navigateTo({
      url: '/pages/wode/edit_user'
    });
  },
})